package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.ProjectInfoReqPara;
import com.lst.entity.response.ProjectInfoResPara;
import com.lst.model.ClientNum;
import com.lst.model.ProjectInfo;
import com.lst.service.ClientNumService;
import com.lst.service.ProjectInfoService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: SearchProjectServlet
 * @Description: 搜索活动接口
 *
 */
public class SearchProjectServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private ProjectInfoService projectInfoService = ctx.getBean(ProjectInfoService.class);

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		ProjectInfoResPara resPara = new ProjectInfoResPara();

		try {
			ProjectInfoReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				String searchwork = reqPara.getSearchwork();
				Integer page = Integer.valueOf(reqPara.getPage());
				Integer pagesize = Integer.valueOf(reqPara.getPagesize());
				
				//根据关键字查询动态列表
				Map<String, Object> reqMap = new HashMap<String, Object>();		
				
				reqMap.put("enabled", true);
				reqMap.put("isDeleted", false);
				reqMap.put("searchwork", searchwork);
				
				PageBounds pageBounds = new PageBounds(page,pagesize);

				//活动
				List<ProjectInfo> pilist = projectInfoService.queryByList(reqMap, pageBounds);
				
				for(ProjectInfo pi : pilist){
					//格式化时间
					String starttime = StringUtils.isEmpty(pi.getStartdate()) ? null : DateUtil.getFormatTime(pi.getStartdate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
					String endtime = StringUtils.isEmpty(pi.getEnddate()) ? null : DateUtil.getFormatTime(pi.getEnddate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
					pi.setStarttime(starttime);			
					pi.setEndtime(endtime);

					//收藏量
					Integer favoritenum = CommFunUtils.opNum(null, pi.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
					//分享量
					Integer sharenum = CommFunUtils.opNum(null, pi.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
					//浏览量
					Map<String, Object> promap = new HashMap<String, Object>();
					
					promap.put("enabled", true);
					promap.put("isDeleted", false);	
					promap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
					promap.put("actid", pi.getId());
					promap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);
					
					List<ClientNum> browselist = clientNumService.queryByList(promap);
					
					Integer browsenum = 0;
					
					for(ClientNum c : browselist){
						browsenum += c.getNum() == null ? 0 : c.getNum();
					}
					
					pi.setFavoritenum(favoritenum);
					pi.setSharenum(sharenum);
					pi.setBrowsenum(browsenum);
				  }
				
				    resPara.setPilist(pilist);
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001);
				}
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info("ClientDiscussServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ProjectInfoReqPara getReqPara(HttpServletRequest request) {

		ProjectInfoReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ProjectInfoReqPara());

			reqPara = (ProjectInfoReqPara) baseRequest.clone();

			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");
			String searchwork = request.getParameter("searchwork");

			logger.info("reqPara page: " + page);
			logger.info("reqPara pagesize: " + pagesize);
			logger.info("reqPara searchwork: " + searchwork);

			reqPara.setPage(page);
			reqPara.setPagesize(pagesize);
			reqPara.setSearchwork(searchwork);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ProjectInfoReqPara piReqPara = (ProjectInfoReqPara) reqPara;
		ProjectInfoResPara piResPara = (ProjectInfoResPara) resPara;
		   if (StringUtils.isEmpty(piReqPara.getPage())){
			   piResPara.setCode(CommCode.M_A000000);
			   piResPara.setMessage(CommCode.M_P000009);
			} else if (StringUtils.isEmpty(piReqPara.getPagesize())){
				piResPara.setCode(CommCode.M_A000000);
				piResPara.setMessage(CommCode.M_P000010);
			} else if(StringUtils.isEmpty(piReqPara.getSearchwork())){
				piResPara.setCode(CommCode.M_A000000);
				piResPara.setMessage(CommCode.M_F000001);
			}else {
				flag = true;
			}
		return  flag;
	}
}
